<?php
/*
Perlu diproses data2 turunannya jg... 
seperti:
    bunganya, polinasi, dst..
*/
class ReplantingModel{
	private $db;
	private $subbagian;
	
	private $validColumn;

	private $data;

	private $result;

	private $sort_by;
	private $sort_order;

	private $search_keyword;
	private $search_field;

	private $limit;
	
	function ReplantingModel($dbObject){
		$this->subbagian 	= 'replanting';		
		$this->db 			= $dbObject;

		$this->validColumn  = array(
			'tgl_penanaman', 
			'no_pancang', 
			'no_individu', 
			'replika', 
			'usia_saat_tanam', 
			'cross_asal_pokok', 
			'jenis_tanaman', 
			'kategori_pokok',
			'penanggung_jawab', 
			'jml_pekerja',
			'biaya_pekerja',
			'kondisi_awal',
			'catatan',
			
			'nama_peralatan',
			'jml_peralatan',
			'nama_material',
			'jml_material',
			'satuan_material'
			);
		
	
		// settting up configuration
		if(($this->start=$this->getGET('start')) == NULL)
			$this->start = 0;

		$this->sort_by 			= $this->getGET('sort_by');
		$this->sort_order 		= $this->getGET('sort_order');
		$this->search_keyword	= $this->getGET('search_keyword');
		$this->search_field		= $this->getGET('search_field');

		if(($this->limit=$this->getGET('limit')) == NULL)
			$this->limit = 50;				
	}

	private function getGET($param){
		if( isset( $_GET[$param] ) && $_GET[$param] != '' )
			return $_GET[$param];
		else
			return NULL;
	}

	private function format($data){
		$result = array();
		foreach($this->validColumn as $v){
			if( isset($data[$v]) )
				$result[$v] = $data[$v];
			else
				$result[$v] = NULL;
		}
		
		return $result;
	}
   
    private function moveOldData(){
        // penanaman
        $q = "
            INSERT INTO caramel_historical.penanaman 
                (`tgl_penanaman`, 
                `no_pancang`, 
                `no_individu`, 
                `replika`, 
                `usia_saat_tanam`, 
                `cross_asal_pokok`, 
                `jenis_tanaman`, 
                `kategori_pokok`,
                `penanggung_jawab`, 
                `jml_pekerja`,
                `biaya_pekerja`,
                `kondisi_awal`,
                `catatan`)
                (SELECT 
                    `tgl_penanaman`, 
                    `no_pancang`, 
                    `no_individu`, 
                    `replika`, 
                    `usia_saat_tanam`, 
                    `cross_asal_pokok`, 
                    `jenis_tanaman`, 
                    `kategori_pokok`,
                    `penanggung_jawab`, 
                    `jml_pekerja`,
                    `biaya_pekerja`,
                    `kondisi_awal`,
                    `catatan`
                FROM caramel_operational.penanaman WHERE no_pancang='".$this->data['no_pancang']."')
            ";
        $this->db->query($q);
        
        // id
        $q = "SELECT MAX(id) as id FROM caramel_historical.penanaman";
        $new_id = $this->db->get_var($q);
        $q = "SELECT id FROM caramel_operational.penanaman WHERE no_pancang='".$this->data['no_pancang']."'";
        $old_id = $this->db->get_var($q);
        
        // material
        $q = "SELECT * FROM caramel_operational.penanaman_material WHERE penanaman_id='$old_id'";
        $r = $this->db->get_results($q, ARRAY_A);
        
		if( count($r) > 0 ){
            foreach($r as $data){
                $q = "
                    INSERT INTO caramel_historical.penanaman_material 
                    (`penanaman_id`, `nama`, `jumlah`, `satuan`) VALUES
                    ('$new_id', '".$data['nama']."','".$data['jumlah']."','".$data['satuan']."')
                    ";
                $this->db->query($q);
            }
        }
        
        // peralatan
        $q = "SELECT * FROM caramel_operational.penanaman_peralatan WHERE penanaman_id='$old_id'";
        $r = $this->db->get_results($q, ARRAY_A);
        
		if( count($r) > 0 ){
            foreach($r as $data){
                $q = "
                    INSERT INTO caramel_historical.penanaman_peralatan 
                    (`penanaman_id`, `nama`, `jumlah`) VALUES
                    ('$new_id', '".$data['nama']."','".$data['jumlah']."')
                    ";
                $this->db->query($q);
            }
        }
        
        // deleting
        $q = "SELECT id FROM caramel_operational.penanaman WHERE no_pancang='".$this->data['no_pancang']."'";
        $id = $this->db->get_var($q);
        
        // penanaman
        $this->deletePenanaman($id);
        // material
        $this->deleteMaterial($id);
        // peralatan
        $this->deletePeralatan($id);
    }
    
    private function deletePenanaman($id){
        $q = "
        DELETE FROM `caramel_operational`.`penanaman` 
        WHERE `id`='$id'";
        
        $this->db->query($q);
    }
    
    private function deletePeralatan($penanaman_id){
        $q = "
        DELETE FROM `caramel_operational`.`penanaman_peralatan` 
        WHERE `penanaman_id`='$penanaman_id'
        ";
        
        $this->db->query($q);
    }
    
    private function deleteMaterial($penanaman_id){
        $q = "
        DELETE FROM `caramel_operational`.`penanaman_material` 
        WHERE `penanaman_id`='$penanaman_id'
        ";
        
        $this->db->query($q);
    }
	
	private function updatePancang($noPancang, $noIndividu){
		$q = "SELECT COUNT(*) FROM `caramel_managerial`.`pancang` WHERE `no_pancang`='".$noPancang."'";
		if( $this->db->get_var($q) > 0 )
			$q = "UPDATE `caramel_managerial`.`pancang` SET `no_individu`='".$noIndividu."' WHERE `no_pancang`='".$noPancang."'";
		else
			$q = "INSERT INTO `caramel_managerial`.`pancang` (`no_pancang`, `no_individu`) VALUES ('".$noPancang."', '".$noIndividu."')";
		
		$this->db->query($q);
	}
	
    private function insertPenanaman(){
		$dataPenanaman = array();
		$penanamanColumn = array(
			'tgl_penanaman', 
			'no_pancang', 
			'no_individu', 
			'replika', 
			'usia_saat_tanam', 
			'cross_asal_pokok', 
			'jenis_tanaman', 
			'kategori_pokok',
			'penanggung_jawab', 
			'jml_pekerja',
			'biaya_pekerja',
			'kondisi_awal',
			'catatan'
		);
		
		// copy dari $data ke $dataPenanaman
		foreach($penanamanColumn as $c){
			$dataPenanaman[$c] = $this->data[$c];
		}
		
		$qHeader = "(`".implode($penanamanColumn, "`, `")."`)";
		$qBody   = "('".implode($dataPenanaman, "', '")."')";
		
		$query = "INSERT INTO `caramel_operational`.`penanaman` ".$qHeader." VALUES ".$qBody;
		$this->db->query($query);
		
		$id = $this->db->get_var("SELECT MAX(`Id`) FROM `caramel_operational`.`penanaman`");
		
		return $id;
	}
    
	private function insertMaterial($id){
		$dataMaterial = array();
		$materialColumn = array(
			'nama_material', 
			'jml_material', 
			'satuan_material'
		);
		
		// copy dari $data ke $dataMaterial
		foreach($materialColumn as $c){
			$dataMaterial[$c] = $this->data[$c];
		}
		
		if( count($dataMaterial['nama_material']) > 0 ){
		
			$qHeader = "(`penanaman_id`, `nama`, `jumlah`, `satuan`)";			
			$query   = "INSERT INTO `caramel_operational`.`penanaman_material` ".$qHeader." VALUES ";
			$temp    = '';
			// looping through all material
			for($i=0; $i<count($dataMaterial['nama_material']); $i++){			
				$qBody   = "('".$id."', '".$dataMaterial['nama_material'][$i]."', '".$dataMaterial['jml_material'][$i]."', '".$dataMaterial['satuan_material'][$i]."')";
				$temp[]  = $qBody;
			}
			
			$query .= implode($temp, ",").';';
			
			$this->db->query($query);
		}
	}
	
	private function insertPeralatan($id){
		$dataPeralatan = array();
		$peralatanColumn = array(
			'nama_peralatan', 
			'jml_peralatan'
		);
		
		// copy dari $data ke $dataPeralatan
		foreach($peralatanColumn as $c){
			$dataPeralatan[$c] = $this->data[$c];
		}
		
		if( count($dataPeralatan['nama_peralatan']) > 0 ){
		
			$qHeader = "(`penanaman_id`, `nama`, `jumlah`)";			
			$query   = "INSERT INTO `caramel_operational`.`penanaman_peralatan` ".$qHeader." VALUES ";
			$temp    = '';
			// looping through all material
			for($i=0; $i<count($dataPeralatan['nama_peralatan']); $i++){			
				$qBody   = "('".$id."', '".$dataPeralatan['nama_peralatan'][$i]."', '".$dataPeralatan['jml_peralatan'][$i]."')";
				$temp[]  = $qBody;
			}
			
			$query .= implode($temp, ",").';';
			
			$this->db->query($query);
		}
	}
	
	function put($data){		
		$this->data	= $this->format($data);// ambil  field2 yang dibutuhkan saja	
		
		if( $this->isExist() != TRUE ){
			// replanting.. 
            // move old data...
			$this->moveOldData();
            
            // insert new one
            $id = $this->insertPenanaman();
			// material
			$this->insertMaterial($id);		
			// peralatan
			$this->insertPeralatan($id);		
			// update pancang
			$this->updatePancang($this->data['no_pancang'], $this->data['no_individu']);
		}
		else{
			return UPDATE_FAIL;
		}
	}	
	
	function isExist(){
		$query = "SELECT COUNT(*) FROM `caramel_managerial`.`pancang` WHERE `no_individu`='".$this->data['no_individu']."' AND `no_pancang`<>'".$this->data['no_pancang']."'";	
		$count = $this->db->get_var($query);
		
		if( $count > 0 )
			return TRUE;
			
		return FALSE; // tidak ada data yang dicari... no duplicate
	}
 
}
?>